import React from 'react';
import { Table, Input, Popconfirm, Form, Button, message } from 'antd';
import { DividerContainer } from '@/molecules';
import { useRequest, defaultFormatResult } from '@/hooks';
import { getGradeList } from '@/services/organization';
import { Icon } from '../../../components';
import EvaluationItemTable from './EvaluationItemTable';
import styles from './index.less';
import DescItem from './DescItem';

const EditableContext = React.createContext();

const EditItem = props => {
    const { editing, dataIndex, title, record, index, children, gradeList, ...restProps } = props;
    const context = React.useContext(EditableContext);
    const { form } = context;
    const { getFieldDecorator } = form;

    const getItem = () => {
        if (dataIndex === 'itemDesc') {
            const { itemDesc } = record;
            return <EvaluationItemTable form={form} dataSource={itemDesc || []} gradeList={gradeList} />;
        }

        return (
            <Form.Item style={{ margin: 0 }}>
                {getFieldDecorator(dataIndex, {
                    rules: [
                        {
                            required: true,
                            message: `请输入${title}`,
                            whitespace: true
                        }
                    ],
                    initialValue: (record && record[dataIndex]) || ''
                })(<Input placeholder={`请输入${title}`} maxLength={15} />)}
            </Form.Item>
        );
    };

    const renderCell = () => {
        if (editing) {
            return <td {...restProps}>{getItem()}</td>;
        }

        return <td {...restProps}>{children}</td>;
    };

    return <EditableContext.Consumer>{renderCell}</EditableContext.Consumer>;
};

const EvaluationTable = ({ form: tempForm, dataSource, onChange, onEditing }) => {
    const { data: gradeList } = useRequest(getGradeList, {
        ...defaultFormatResult
    });

    const gradeMap = React.useMemo(() => {
        if (!gradeList) {
            return {};
        }
        const obj = {};
        gradeList.forEach(item => {
            obj[item.rankCode] = item;
        });
        return obj;
    }, [gradeList]);

    const [data, setData] = React.useState(dataSource || []);
    const [editingKey, setEditingKey] = React.useState('');

    const isEditing = record => record.id === editingKey;

    React.useEffect(() => {
        if (onChange) {
            onChange(data);
        }
    }, [data]);

    React.useEffect(() => {
        if (onEditing) {
            onEditing(editingKey);
        }
    }, [editingKey]);

    React.useEffect(() => {
        if (!dataSource || JSON.stringify(dataSource) === JSON.stringify(data)) {
            return;
        }
        setData(dataSource);
    }, [dataSource]);

    const getFinalItem = values => {
        const tempArr = [];
        [1, 2, 3, 4, 5].forEach(item => {
            if (values?.[`score${item}`] && values?.[`score${item}`].length > 0) {
                tempArr.push(item);
            }
        });

        return tempArr.map(item => ({
            scoreValue: item,
            rankCodes: values?.[`score${item}`] ? values?.[`score${item}`].join(',') : '',
            rankValues: values?.[`score${item}`]
                ? values?.[`score${item}`].map(o => gradeMap[o].rankValue).join(',')
                : '',
            comment: values?.[`comment${item}`]
        }));
    };

    const handleSave = (form, key) => {
        tempForm.validateFields((error, row) => {
            // console.log('🚀 ~ tempForm.validateFields ~ row', row);
            if (error) {
                return;
            }
            const newData = [...data];
            const index = newData.findIndex(item => key === item.id);
            if (index > -1) {
                const item = newData[index];
                const { itemName } = row;
                const itemDesc = getFinalItem(row);
                if (itemDesc && itemDesc.length > 0) {
                    newData.splice(index, 1, {
                        ...item,
                        itemName,
                        itemDesc
                    });
                } else {
                    message.error('请添加至少一项评分标准');
                    return;
                }
            }
            setData(newData);
            setEditingKey('');
        });
    };

    const handleCancel = key => {
        const newData = [...data];
        const index = newData.findIndex(item => key === item.id);
        if (newData[index].itemName) {
            setEditingKey('');
        } else {
            newData.splice(index, 1);
            setData(newData);
            setEditingKey('');
        }
    };

    const handleEdit = key => {
        setEditingKey(key);
    };

    const handleDelete = key => {
        const newData = [...data];
        const index = newData.findIndex(item => key === item.id);
        if (index > -1) {
            newData.splice(index, 1);
        }
        setData(newData);
        setEditingKey('');
    };

    const handleAdd = () => {
        const newData = [...data];
        const tempKey = new Date().getTime().toString();
        newData.push({
            id: tempKey,
            itemName: '',
            itemDesc: ''
        });
        setData(newData);
        setEditingKey(tempKey);
    };

    const columns = [
        {
            title: '评估项',
            dataIndex: 'itemName',
            editable: true
        },
        {
            title: '总分',
            dataIndex: 'id',
            width: 60,
            render: () => '5'
        },
        {
            title: '评分标准',
            dataIndex: 'itemDesc',
            width: '60%',
            editable: true,
            render: text => <DescItem text={text} />
        },
        {
            title: '操作',
            dataIndex: 'operation',
            width: 130,
            render: (text, record) => {
                const editable = isEditing(record);
                return editable ? (
                    <DividerContainer>
                        <EditableContext.Consumer>
                            {form => <Icon title="保存" type="confirm_o" onClick={() => handleSave(form, record.id)} />}
                        </EditableContext.Consumer>
                        <Icon title="取消" type="cancel_o" onClick={() => handleCancel(record.id)} />
                    </DividerContainer>
                ) : (
                    <DividerContainer>
                        <Icon
                            title="编辑"
                            disabled={editingKey !== ''}
                            type="listfunction_edit_icon_default"
                            onClick={() => handleEdit(record.id)}
                        />
                        <Popconfirm title="确定删除吗？" onConfirm={() => handleDelete(record.id)}>
                            <Icon
                                title="删除"
                                disabled={editingKey !== ''}
                                type="listfunction_delete_icon_default"
                                onClick={() => {}}
                            />
                        </Popconfirm>
                    </DividerContainer>
                );
            }
        }
    ];

    const realColumns = columns.map(col => {
        if (!col.editable) {
            return col;
        }
        return {
            ...col,
            onCell: record => ({
                record,
                dataIndex: col.dataIndex,
                title: col.title,
                gradeList,
                editing: isEditing(record)
            })
        };
    });

    const components = {
        body: {
            cell: EditItem
        }
    };

    return (
        <EditableContext.Provider value={{ form: tempForm }}>
            <Table
                rowKey="id"
                bordered={false}
                components={components}
                dataSource={data}
                columns={realColumns}
                rowClassName={styles.editableRow}
                pagination={false}
            />
            <Button
                type="dashed"
                icon="plus"
                block
                disabled={editingKey !== '' || data?.length >= 20}
                style={{ marginTop: 24 }}
                onClick={handleAdd}
            >
                添加
            </Button>
        </EditableContext.Provider>
    );
};

export default Form.create()(EvaluationTable);
